package work

import (
	"sync"
	"time"

	kadefine "kiwi/actor/define"
)

const (
	DefaultDispatchTimeout = 30 * time.Second
)

type IPostWork interface {
	Execute(ctx kadefine.Context)
}

type PostFunc func(ctx kadefine.Context)

func (f PostFunc) Execute(ctx kadefine.Context) {
	f(ctx)
}

type IDispatchWork interface {
	Execute(ctx kadefine.Context) error
}

type DispatchFunc func(ctx kadefine.Context) error

func (f DispatchFunc) Execute(ctx kadefine.Context) error {
	return f(ctx)
}

type MessagePostWork struct {
	Work IPostWork
}

var gMessagePostWorkPool = sync.Pool{}

func CreateMessagePostWork(work IPostWork) *MessagePostWork {
	m, ok := gMessagePostWorkPool.Get().(*MessagePostWork)
	if ok && m != nil {
		m.Work = work
	} else {
		m = &MessagePostWork{
			Work: work,
		}
	}
	return m
}

func DestroyMessagePostWork(m *MessagePostWork) {
	if m == nil {
		return
	}
	m.Work = nil
	gMessagePostWorkPool.Put(m)
}

type MessageDispatchWork struct {
	Err  error
	Work IDispatchWork
}

var gMessageDispatchWorkPool = sync.Pool{}

func CreateMessageDispatchWork(work IDispatchWork) *MessageDispatchWork {
	m, ok := gMessageDispatchWorkPool.Get().(*MessageDispatchWork)
	if ok && m != nil {
		m.Err = nil
		m.Work = work
	} else {
		m = &MessageDispatchWork{
			Work: work,
		}
	}
	return m
}

func DestroyMessageDispatchWork(m *MessageDispatchWork) {
	if m == nil {
		return
	}
	m.Err = nil
	m.Work = nil
	gMessageDispatchWorkPool.Put(m)
}
